package main

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"go-web-learning/src/05_grpc/4_stream/stream"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/grpclog"
	"io"
	"os"
)

func main() {
	bothStreamClient()
}

func streamServerClient() {
	addr := ":8080"
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		grpclog.Fatalf("Fail to dial %s: %s", addr, err.Error())
	}
	defer conn.Close()

	client := stream.NewServiceStreamClient(conn)
	streamResp, err := client.Downloads(context.Background(), &stream.Request{Name: "啊哈哈"})
	file, err := os.OpenFile("src/05_grpc/4_stream/static/wget-log_copy", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0777)
	if err != nil {
		grpclog.Fatalf("Failed to downloads file: %s", err.Error())
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	for i := 0; ; i++ {
		resp, err := streamResp.Recv()
		if errors.Is(err, io.EOF) {
			break
		} else if !errors.Is(err, nil) {
			grpclog.Fatalf("Failed to downloads file: %s", err.Error())
		}
		writer.Write(resp.Content)
		fmt.Printf("第%02d次 写入数据长度: %d\n", i+1, len(resp.Content))
	}
	writer.Flush()
}

func streamClientClient() {
	addr := ":8080"
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		grpclog.Fatalf("Fail to dial %s: %s", addr, err.Error())
	}
	defer conn.Close()

	client := stream.NewClientStreamClient(conn)
	s, err := client.Uploads(context.Background())
	file, err := os.Open("src/05_grpc/4_stream/static/pic.png")
	if err != nil {
		grpclog.Fatalf("Failed to read file: %s", err.Error())
	}
	for {
		buf := make([]byte, 1024)
		_, err = file.Read(buf)
		if errors.Is(err, io.EOF) {
			break
		} else if !errors.Is(err, nil) {
			return
		}
		s.Send(&stream.FileRequest{FileName: "pic_uploads.png", Content: buf})
	}
	recv, err := s.CloseAndRecv()
	fmt.Println(recv, err)
}

func bothStreamClient() {
	addr := ":8080"
	conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		grpclog.Fatalf("Fail to dial %s: %s", addr, err.Error())
	}
	defer conn.Close()

	client := stream.NewBothStreamClient(conn)
	s, err := client.Chat(context.Background())
	for i := 0; i < 10; i++ {
		fmt.Println("-------start-------")
		s.Send(&stream.Request{Message: fmt.Sprintf("client msg No.%02d", i+1)})
		response, _ := s.Recv()
		fmt.Printf("receive server msg: %s\n", response.Message)
		fmt.Println("--------end--------")
	}
}
